/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package java_swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author 08651_000
 */
public class Bai06_Button2 extends JFrame implements ActionListener {

    private JLabel lb;
    private JButton button, button1;

    public Bai06_Button2() {
        this.setSize(500, 500);
        setLocation(300, 300);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lb = new JLabel("I'm Vincent");
        add(lb);
        lb.setSize(500, 500);
        //configPicture(lb, "img\\test.jpg");

        button = new JButton("Test 1");
        add(button, "North", 1);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                configPicture(lb, "img\\test1.jpg");
            }
        });
        
        
        button1 = new JButton("Test 2");
        add(button1, "South", 1);
        button1.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton b = (JButton) e.getSource();
        if (b == button1) {
            configPicture(lb, "img\\test2.jpg");
        } 

    }

    public void configPicture(JLabel lb, String filename) {
        try {
            BufferedImage buffer = ImageIO.read(new File(filename));
            int x = lb.getSize().width;
            int y = lb.getSize().height;
            int ix = buffer.getWidth();
            int iy = buffer.getHeight();
            int dx = 0;
            int dy = 0;
            if (x / y > ix / iy) {
                dy = y;
                dx = dy * ix / iy;
            } else {
                dx = x;
                dy = dx * iy / ix;
            }
            System.out.println(dx + " - " + dy);
            ImageIcon imgIcon = new ImageIcon(buffer.getScaledInstance(dx, dy, buffer.SCALE_SMOOTH));
            lb.setIcon(imgIcon);
        } catch (IOException ex) {
            Logger.getLogger(Bai04_ImageIcon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        Bai06_Button2 bai5 = new Bai06_Button2();
        bai5.setVisible(true);
    }
}
